package com.example.demo.flashsale;

import com.example.demo.common.Constant;
import com.example.demo.common.IdGenerator;
import com.example.demo.common.OrderReq;
import com.example.demo.repo.RepertoryCache;
import com.example.demo.repo.RepertoryRepo;
import com.example.demo.repo.model.Order;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

import static org.apache.rocketmq.client.producer.SendStatus.SEND_OK;

@RestController
@RequestMapping("/flashSale")
public class FlashSaleController {

    private RepertoryRepo repertoryRepo;
    private RepertoryCache repoCache;
    private RocketMQTemplate mqTemplate;
    private IdGenerator idGenerator;

    public FlashSaleController(RepertoryRepo repertoryRepo,
                               RepertoryCache repoCache,
                               RocketMQTemplate mqTemplate,
                               IdGenerator idGenerator) {
        this.repertoryRepo = repertoryRepo;
        this.repoCache = repoCache;
        this.mqTemplate = mqTemplate;
        this.idGenerator = idGenerator;
    }

    // 获取商品库存
    @GetMapping("/repos")
    public Map<Long, Integer> getRepos() {
        Map<Long, Integer> result = repoCache.getRepos();
        if (result.size() == 0) {
            // 初始化库存
            result = repertoryRepo.getRepos();
            repoCache.initRepo(result);
        }

        return result;
    }

    // 抢购
    @PostMapping("/purchase")
    public Long purchase(@RequestBody OrderReq req) {

        // 库存验证
        repoVerify(req);

        // 生成订单并发送到待处理
        Order order = genPreviewOrder(req);
        sendOrder(order);

        return order.getOrderId();
    }

    void repoVerify(OrderReq req) {
        Integer repo = repoCache.getNumbers(req.getProductId());
        if (repo == null) {
            throw new RuntimeException("商品不存在");
        }
        if (repo < req.getNumbers()) {
            throw new RuntimeException("商品已卖光");
        }
    }

    Order genPreviewOrder(OrderReq req) {
        Order order = new Order();
        order.setProductId(req.getProductId());
        order.setNumbers(req.getNumbers());

        order.setOrderId(idGenerator.genId());
        order.setOrderStatus(Order.OrderStatus.not_pay);
        order.setCreateTime(new Date().getTime());

        return order;
    }

    void sendOrder(Order order) {
        SendResult sendResult = mqTemplate.syncSend(Constant.ORDER_PREVIEW, order);
        if (sendResult.getSendStatus() != SEND_OK) {
            throw new RuntimeException("订单创建失败");
        }
    }
}
